#include "registerdialog.h"
#include "ui_registerdialog.h"
#include"global.h"
#include"httpmgr.h"

RegisterDialog::RegisterDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::RegisterDialog)
{
    ui->setupUi(this);
    ui->pass_edit->setEchoMode(QLineEdit::Password);
    ui->pass2_edit->setEchoMode(QLineEdit::Password);
    ui->err_tip_label->setProperty("state", "normal");
    repolish(ui->err_tip_label);

    connect(HttpMgr::GetInstance().get(), &HttpMgr::sig_reg_mod_finish, this, &RegisterDialog::slot_reg_mod_finish);
    initHttpHandlers();

//    先清空错误提示
    ui->err_tip_label->clear();

    connect(ui->user_edit,&QLineEdit::editingFinished,this,[this](){
        checkUserValid();
    });

    connect(ui->email_edit, &QLineEdit::editingFinished, this, [this](){
        checkEmailValid();
    });

    connect(ui->pass_edit, &QLineEdit::editingFinished, this, [this](){
        checkPassValid();
    });

    connect(ui->pass2_edit, &QLineEdit::editingFinished, this, [this](){
        checkPass2Valid();
    });

    connect(ui->verify_edit, &QLineEdit::editingFinished, this, [this](){
        checkVerifyValid();
    });

    //设置浮动显示手形状
    ui->pass_visiable_label->setCursor(Qt::PointingHandCursor);
    ui->pass2_visiable_label->setCursor(Qt::PointingHandCursor);

    ui->pass_visiable_label->SetState("unvisible","unvisible_hover","","visible",
                                "visible_hover","");

    ui->pass2_visiable_label->SetState("unvisible","unvisible_hover","","visible",
                                    "visible_hover","");
    //连接点击事件

    connect(ui->pass_visiable_label, &ClickedLabel::clicked, this, [this]() {
        auto state = ui->pass_visiable_label->GetCurState();
        if(state == ClickLbState::Normal){
            ui->pass_edit->setEchoMode(QLineEdit::Password);
        }else{
                ui->pass_edit->setEchoMode(QLineEdit::Normal);
        }
        qDebug() << "Label was clicked!";
    });

    connect(ui->pass2_visiable_label, &ClickedLabel::clicked, this, [this]() {
        auto state = ui->pass2_visiable_label->GetCurState();
        if(state == ClickLbState::Normal){
            ui->pass2_edit->setEchoMode(QLineEdit::Password);
        }else{
                ui->pass2_edit->setEchoMode(QLineEdit::Normal);
        }
        qDebug() << "Label was clicked!";
    });
}

RegisterDialog::~RegisterDialog()
{
    delete ui;
}

void RegisterDialog::on_get_code_btn_clicked()
{
    auto email = ui->email_edit->text();
    QRegularExpression regex(R"((\w+)(\.|_)?(\w*)@(\w+)(\.(\w+))+)");
    bool match = regex.match(email).hasMatch();
    if(match)
    {
        QJsonObject json_obj;
        json_obj["email"] = email;
        HttpMgr::GetInstance()->PostHttpReq(QUrl(gate_url_prefix + "/get_verifycode"),
                                            json_obj, ReqId::ID_GET_VERIFY_CODE, Modules::REGISTER_MOD);
    }
    else
    {
        showTip(tr("邮箱地址不正确"), false);
    }
}

void RegisterDialog::slot_reg_mod_finish(ReqId id, QString res, ErrorCodes err)
{
    if(err != ErrorCodes::SUCCESS)
    {
        showTip(tr("网络请求错误"), false);
        return ;
    }
    QJsonDocument jsonDoc = QJsonDocument::fromJson(res.toUtf8());
    if(jsonDoc.isNull())
    {
        showTip(tr("json解析错误"), false);
        return;
    }

    if(!jsonDoc.isObject())
    {
        showTip(tr("json解析错误"), false);
        return;
    }

    QJsonObject jsonObj = jsonDoc.object();

    _handlers[id](jsonObj);
    return;
}

void RegisterDialog::initHttpHandlers()
{
    _handlers.insert(ReqId::ID_GET_VERIFY_CODE, [this](QJsonObject jsonObj){
       int error = jsonObj["error"].toInt();
       if(error != ErrorCodes::SUCCESS)
       {
           showTip(tr("参数错误"), false);
           return ;
       }
       auto email = jsonObj["email"].toString();
       showTip("验证码已发送邮箱，注意查收", true);
       qDebug() << "email is" << email;
       return;
    });
    _handlers.insert(ReqId::ID_REG_USER, [this](QJsonObject jsonObj){
       int error = jsonObj["error"].toInt();
       if(error != ErrorCodes::SUCCESS) {
            showTip(tr("参数错误"), false);
            return;
       }
        showTip(tr("用户注册成功"), true);
        qDebug() << "返回结果：" << jsonObj;
    });
}

void RegisterDialog::showTip(QString str, bool b_ok)
{
    if(b_ok)
    {
        ui->err_tip_label->setProperty("state", "normal");
    }
    else
    {
        ui->err_tip_label->setProperty("state", "err");
    }
    ui->err_tip_label->setText(str);
    repolish(ui->err_tip_label);
}

void RegisterDialog::on_confirm_btn_clicked()
{
    bool valid = checkUserValid();
    if(!valid){
        return;
    }

    valid = checkEmailValid();
    if(!valid){
        return;
    }

    valid = checkPassValid();
    if(!valid){
        return;
    }

    valid = checkPass2Valid();
    if(!valid){
        return;
    }

    valid = checkVerifyValid();
    if(!valid){
        return;
    }

    QJsonObject json_obj;
    json_obj["user"] = ui->user_edit->text();
    json_obj["email"] = ui->email_edit->text();
    json_obj["passwd"] = ui->pass_edit->text();
    json_obj["passwd2"] = ui->pass2_edit->text();
    json_obj["verifyCode"] = ui->verify_edit->text();
    HttpMgr::GetInstance()->PostHttpReq(QUrl(gate_url_prefix + "/user_register"),
                                        json_obj, ReqId::ID_REG_USER, Modules::REGISTER_MOD);
}

void RegisterDialog::AddTipErr(TipErr te, QString tips)
{
    _tip_errs[te] = tips;
    showTip(tips, false);
}

void RegisterDialog::DelTipErr(TipErr te)
{
    _tip_errs.remove(te);
    if(_tip_errs.empty()){
      ui->err_tip_label->clear();
      return;
    }

    showTip(_tip_errs.first(), false);
}

void RegisterDialog::ChangeTipPage()
{

}

bool RegisterDialog::checkUserValid()
{
    if(ui->user_edit->text() == ""){
           AddTipErr(TipErr::TIP_USER_ERR, tr("用户名不能为空"));
           return false;
       }

   DelTipErr(TipErr::TIP_USER_ERR);
   return true;
}

bool RegisterDialog::checkPassValid()
{
    auto pass = ui->pass_edit->text();

    if(pass.length() < 6 || pass.length()>15){
        //提示长度不准确
        AddTipErr(TipErr::TIP_PWD_ERR, tr("密码长度应为6~15"));
        return false;
    }

    // 创建一个正则表达式对象，按照上述密码要求
    // 这个正则表达式解释：
    // ^[a-zA-Z0-9!@#$%^&*]{6,15}$ 密码长度至少6，可以是字母、数字和特定的特殊字符
    QRegularExpression regExp("^[a-zA-Z0-9!@#$%^&*]{6,15}$");
    bool match = regExp.match(pass).hasMatch();
    if(!match){
        //提示字符非法
        AddTipErr(TipErr::TIP_PWD_ERR, tr("不能包含非法字符"));
        return false;;
    }

    DelTipErr(TipErr::TIP_PWD_ERR);

    return true;
}

bool RegisterDialog::checkPass2Valid()
{
   if(ui->pass_edit->text() != ui->pass2_edit->text()) {
       AddTipErr(TipErr::TIP_PWD2_ERR, tr("密码和二次输入密码不匹配"));
       return false;
   }

    DelTipErr(TipErr::TIP_PWD2_ERR);
    return true;
}

bool RegisterDialog::checkEmailValid()
{
    //验证邮箱的地址正则表达式
    auto email = ui->email_edit->text();
    // 邮箱地址的正则表达式
    QRegularExpression regex(R"((\w+)(\.|_)?(\w*)@(\w+)(\.(\w+))+)");
    bool match = regex.match(email).hasMatch(); // 执行正则表达式匹配
    if(!match){
        //提示邮箱不正确
        AddTipErr(TipErr::TIP_EMAIL_ERR, tr("邮箱地址不正确"));
        return false;
    }

    DelTipErr(TipErr::TIP_EMAIL_ERR);
    return true;
}

bool RegisterDialog::checkVerifyValid()
{
    auto pass = ui->verify_edit->text();
    if(pass.isEmpty()){
        AddTipErr(TipErr::TIP_VARIFY_ERR, tr("验证码不能为空"));
        return false;
    }

    DelTipErr(TipErr::TIP_VARIFY_ERR);
    return true;
}


